package cn.yiya.shiji.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.yiya.shiji.R;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.QiNiuCloud;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.User;
import cn.yiya.shiji.netroid.Netroid;
import cn.yiya.shiji.utils.BitmapTool;
import cn.yiya.shiji.utils.Util;
import cn.yiya.shiji.views.RoundedNormalIV;

public class EditUserInfoActivity extends BaseAppCompatActivity implements View.OnClickListener {

	private ImageView ivBack;
	private TextView tvTitle;
	private TextView tvSave;

	private LinearLayout llytHead;
	private RoundedNormalIV headImage;

	private EditText etName;

	private boolean isBusy;
	private Bitmap photo;
	private int user_id;
	private String key;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_userinfo_edit);
		initViews();
		initEvents();
		init();
	}

	public void getUserInfo(){
		new RetrofitRequest<User>(ApiRequest.getApiShiji().getUserDetail()).handRequest(new MsgCallBack() {
			@Override
			public void onResult(HttpMessage msg) {
				if (msg.isSuccess()) {
					User mUser = (User) msg.obj;
					if (mUser != null) {
						etName.setText(mUser.getName() + "");
						etName.setSelection(etName.getText().length());
						Netroid.displayImage(Util.transfer(mUser.getHead()), headImage, R.mipmap.user_icon_default);
						user_id = mUser.getUser_id();
					}
				} else {
					showTips(msg.message);
				}
			}
		});
	}

	// 调用系统裁剪图片
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 340);
		intent.putExtra("outputY", 340);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 1112);
	}

	// 上传头像或者名字到服务器
	private void upLoadToServer(Bitmap photo, final String name) {

		if(TextUtils.isEmpty(name)){
			showTips("名字不能为空");
			return;
		}

		showPreDialog("正在保存修改");

		if (photo != null) {
			key = user_id + "_avatar_" + System.currentTimeMillis();
			QiNiuCloud.getInstance().upLoadToServer(BitmapTool.Bitmap2Bytes(photo), key, new MsgCallBack() {
				@Override
				public void onResult(HttpMessage msg) {
					if(msg.isSuccess()){
						upLoadNameToServer(name);
					}else {
						hidePreDialog();
						showTips(msg.message);
					}
				}
			});
		} else {
			upLoadNameToServer(name);
		}
	}

	// 保存名字数据
	private void upLoadNameToServer(final String name) {
		new RetrofitRequest<>(ApiRequest.getApiShiji().changeName(name)).handRequest(new MsgCallBack() {
			@Override
			public void onResult(HttpMessage msg) {
				hidePreDialog();
				if(msg.isSuccess()){
					Intent intent = new Intent();
					if(photo != null){
						intent.putExtra("photo", photo);
					}
					intent.putExtra("name", name);
					setResult(RESULT_OK, intent);
					finish();
					showTips("修改成功");
				}
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 1111){
			if(resultCode == Activity.RESULT_OK){
				Uri uri = data.getData();
				if (uri != null) {
					startPhotoZoom(uri);
				}else{
					isBusy = false;
				}
			}else{
				isBusy = false;
				return;
			}
		} else if(requestCode == 1112){
			isBusy = false;
			if(resultCode != Activity.RESULT_CANCELED && data != null){
				if(data.getExtras() != null){
					photo = data.getExtras().getParcelable("data");
					headImage.setImageBitmap(photo);							//(drawable);
				}
			}
		}
	}
		
	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.title_back:
				onBackPressed();
				break;
			case R.id.title_right:
				upLoadToServer(photo, etName.getText().toString());
				break;
			case R.id.llt_headImage:
				if(isBusy){
					break;
				}
				isBusy = true;
				try {
					Intent intent = new Intent(Intent.ACTION_PICK);
					intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
					startActivityForResult(intent, 1111);
				} catch (Exception e){
					showTips("无法调用系统相册");
				}
				break;
		}
	}

	@Override
	public void onBackPressed() {
		setResult(Activity.RESULT_CANCELED);
		finish();
	}

	@Override
	protected void initViews() {
		ivBack = (ImageView) findViewById(R.id.title_back);
		tvTitle = (TextView) findViewById(R.id.title_txt);
		tvTitle.setText("编辑资料");
		tvSave = (TextView) findViewById(R.id.title_right);
		tvSave.setText("保存");
		tvSave.setTextColor(Color.parseColor("#ed5137"));

		llytHead = (LinearLayout) findViewById(R.id.llt_headImage);
		headImage = (RoundedNormalIV) findViewById(R.id.headImage);

		etName = (EditText) findViewById(R.id.etName);
	}

	@Override
	protected void initEvents() {
		ivBack.setOnClickListener(this);
		tvSave.setOnClickListener(this);
		llytHead.setOnClickListener(this);
		etName.setOnClickListener(this);
	}

	@Override
	protected void init() {
		getUserInfo();
	}
}
